package net.hn.hnms.biz.mine.controller;


import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import net.hn.hnms.sys.common.core.utils.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 转化数据中台api接口
 */
@RestController
@RequestMapping("conversionApi")
@Api(value = "转化数据中台api接口控制器", tags = {"转化数据中台api接口"})
public class ConversionApiController {
    @ApiOperation("根据URL获取转化数据中台数据")
    @GetMapping("getDataByUrl")
    public Object UpDataSensorCoordinate(@ApiParam(value = "数据中台URL地址",required = true) String url,
                                         @ApiParam(value = "请求头appToken",required = true) String appToken) {
        if (!StringUtils.isNotBlank(appToken)) {
            appToken = "T3FUUEhJYzh4M1kybmxwYWZOaTQrZXhFUWhiVnFNUExGQVhibjF1c0E=";
        }
        try {
            Object responseData = sendGetRequest(url,appToken, Object.class);
            return responseData;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static <T> T sendGetRequest(String url,String appToken, Class<T> responseType) throws IOException {
        // 创建URL对象
        URL apiUrl = new URL(url);

        // 打开HTTP连接
        HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();

        // 设置请求头
        connection.setRequestProperty("appToken", appToken);

        // 设置请求方法
        connection.setRequestMethod("GET");

        // 获取响应码
        int responseCode = connection.getResponseCode();

        if (responseCode == HttpURLConnection.HTTP_OK) {
            // 读取响应数据
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder responseData = new StringBuilder();

            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                responseData.append(inputLine);
            }

            // 关闭输入流
            in.close();

            // 将JSON字符串解析为对象
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.readValue(responseData.toString(), responseType);
        }
        return null;
    }
}
